package com.cloudinnov.utils;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.cloudinnov.model.AuthUsers;

import redis.clients.jedis.Jedis;

/**
 * @author chengning
 * @date 2016年2月19日上午11:22:16
 * @email ningcheng@cloudinnov.com
 * @remark 登录成功后给前端发一个token，之后前端每次请求都带token了。
 * 前端的请求没带token的，则认为它没有登录，不返回任何数据。
 * @version
 */
public class TokenUtil {

	private static TokenUtil instance = new TokenUtil();

	private long previous;

	protected TokenUtil() {
	}

	public static TokenUtil getInstance() {
		return instance;
	}

	/**
	 * isTokenValid
	 * 
	 * @Description: 判断token是否过期
	 * @param @param request
	 * @param @param reset true表示使用完之后再次生成
	 * @param @return 参数
	 * @return boolean 返回类型
	 */
	public synchronized boolean isTokenValid(HttpServletRequest request,
			HttpServletResponse response, Jedis redisClient, String loginCode,
			boolean reset) {
		String saved = redisClient.get("token:" + loginCode);
		String refreshTime = redisClient.get("refreshTime:" + loginCode);
		if (saved == null) {
			return false;
		}
		if (reset) {
			resetToken(request);
		}
		String token = request.getParameter("token");

		if (token == null
				|| refreshTime == null
				|| (System.currentTimeMillis() - Long.valueOf(refreshTime)) > Long
						.valueOf(PropertiesUtils
								.findPropertiesKey("tokenTimeOut"))) {
			return false;
		} else {
			return saved.equals(token);
		}
	}

	/**
	 * resetToken
	 * 
	 * @Description: 移除session中的token
	 * @param @param request 参数
	 * @return void 返回类型
	 */
	public synchronized void resetToken(HttpServletRequest request) {
		HttpSession session = request.getSession(false);
		if (session == null) {
			return;
		} else {
			EhcacheUtils.remove(session.getAttribute("token"
					+ ((AuthUsers) session.getAttribute("login")).getCode()));
			session.removeAttribute("token"
					+ ((AuthUsers) session.getAttribute("login")).getCode());
			session.removeAttribute("refreshTime"
					+ ((AuthUsers) session.getAttribute("login")).getCode());

			return;
		}
	}

	/**
	 * saveToken
	 * 
	 * @Description: 生成token
	 * @param @param request 参数
	 * @return void 返回类型
	 */
	public synchronized String saveToken() {
		String token = generateToken(CommonUtils.getUUID()
				+ System.currentTimeMillis());
		return token;
	}

	public synchronized String generateToken(HttpServletRequest request) {
		return generateToken(CommonUtils.getUUID() + System.currentTimeMillis());
	}

	public synchronized String generateToken(String id) {
		try {
			long current = System.currentTimeMillis();
			if (current == previous) {
				current++;
			}
			previous = current;
			byte now[] = (new Long(current)).toString().getBytes();
			MessageDigest md5 = MessageDigest.getInstance("MD5");
			md5.update(now);
			byte[] tmp = md5.digest();
			StringBuilder sb = new StringBuilder();
			for (byte b : tmp) {
				sb.append(Integer.toHexString(b & 0xff));
			}
			return sb.toString();
		} catch (NoSuchAlgorithmException e) {
			return null;
		}
	}

}
